import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:permission_handler/permission_handler.dart';
import '../services/ble_peripheral_service.dart';
import 'camera_page.dart';

class BluetoothPage extends StatefulWidget {
  const BluetoothPage({super.key});

  @override
  State<BluetoothPage> createState() => _BluetoothPageState();
}

class _BluetoothPageState extends State<BluetoothPage> {
  final BlePeripheralService _bleService = BlePeripheralService();
  bool _isAdvertising = false;
  String _status = '未启动';
  String _lastCommand = '';
  DateTime? _startTime;
  bool _isInitialized = false;
  Timer? _displayTimer;
  final GlobalKey<CameraPageState> _cameraPageKey = GlobalKey<CameraPageState>();

  @override
  void initState() {
    super.initState();
    _initializeBle();
    _displayTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (mounted && _isAdvertising) {
        setState(() {
          // 触发重建以更新时间显示
        });
      }
    });
  }

  Future<void> _initializeBle() async {
    try {
      // 请求权限
      await _checkPermissions();
      
      await _bleService.initialize();
      
      // 监听命令
      _bleService.commandStream.listen((command) {
        setState(() {
          _lastCommand = command;
        });
        _handleCommand(command);
      });

      // 监听广播状态
      _bleService.onAdvertisingStateChanged = (isAdvertising) {
        setState(() {
          _isAdvertising = isAdvertising;
          _status = isAdvertising ? '正在广播' : '已停止';
          if (isAdvertising) {
            _startTime = DateTime.now();
          } else {
            _startTime = null;
          }
        });
      };

      setState(() {
        _isInitialized = true;
      });

    } catch (e) {
      debugPrint('BLE 初始化错误: $e');
      _showErrorDialog('初始化失败: $e');
    }
  }

  Future<void> _checkPermissions() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.bluetooth,
      Permission.bluetoothAdvertise,
      Permission.bluetoothConnect,
      Permission.bluetoothScan,
    ].request();

    bool allGranted = true;
    statuses.forEach((permission, status) {
      if (!status.isGranted) {
        allGranted = false;
      }
    });

    if (!allGranted) {
      _showPermissionDeniedDialog();
    }
  }

  Future<void> _toggleAdvertising() async {
    try {
      if (!_isAdvertising) {
        await _bleService.startAdvertising();
      } else {
        await _bleService.stopAdvertising();
      }
    } catch (e) {
      debugPrint('切换广播状态错误: $e');
      _showErrorDialog('操作失败: $e');
    }
  }

  void _handleCommand(String command) {
    debugPrint('收到命令: $command');
    
    if (command.startsWith('STOP_RECORDING:')) {
      // 从命令中提取视频名称
      final videoName = command.substring('STOP_RECORDING:'.length);
      debugPrint('收到停止录制命令，视频名称: $videoName');
      
      // 如果在相机页面，发送停止录制命令并带上视频名称
      if (_cameraPageKey.currentState != null) {
        _cameraPageKey.currentState!.stopRecordingWithName(videoName);
      }
    } else {
      switch (command) {
        case 'START_RECORDING':
          // 如果已经在相机页面，发送开始录制命令
          if (_cameraPageKey.currentState != null) {
            _cameraPageKey.currentState!.startRecording();
          } else {
            // 如果不在相机页面，先跳转到相机页面并立即开始录制
            Navigator.push(
              context,
              CupertinoPageRoute(
                builder: (context) => CameraPage(
                  key: _cameraPageKey,
                  startRecordingImmediately: true,  // 相机初始化完成后会自动开始录制
                  onVideoNameReceived: (name) {
                    debugPrint('视频已保存: $name');
                    _bleService.sendVideoName(name);
                  },
                ),
              ),
            );
          }
          break;
        case 'STOP_RECORDING':
          // 如果在相机页面，发送停止录制命令
          if (_cameraPageKey.currentState != null) {
            _cameraPageKey.currentState!.stopRecording();
          }
          break;
      }
    }
  }

  void _navigateToCamera({required bool isRecording}) {
    Navigator.push(
      context,
      CupertinoPageRoute(
        builder: (context) => CameraPage(
          startRecordingImmediately: isRecording,  // 根据参数决定是否立即开始录制
          onVideoNameReceived: (name) {
            debugPrint('视频已保存: $name');
            _bleService.sendVideoName(name);
          },
        ),
      ),
    );
  }

  void _showErrorDialog(String message) {
    showCupertinoDialog(
      context: context,
      builder: (context) => CupertinoAlertDialog(
        title: const Text('错误'),
        content: Text(message),
        actions: [
          CupertinoDialogAction(
            child: const Text('确定'),
            onPressed: () => Navigator.pop(context),
          ),
        ],
      ),
    );
  }

  void _showPermissionDeniedDialog() {
    showCupertinoDialog(
      context: context,
      builder: (context) => CupertinoAlertDialog(
        title: const Text('需要蓝牙权限'),
        content: const Text('请在设置中允许蓝牙权限以继续使用'),
        actions: [
          CupertinoDialogAction(
            child: const Text('取消'),
            onPressed: () => Navigator.pop(context),
          ),
          CupertinoDialogAction(
            isDefaultAction: true,
            child: const Text('去设置'),
            onPressed: () async {
              Navigator.pop(context);
              await openAppSettings();
            },
          ),
        ],
      ),
    );
  }

  String _getRunningTime() {
    if (_startTime == null) return '';
    final difference = DateTime.now().difference(_startTime!);
    final minutes = difference.inMinutes;
    final seconds = difference.inSeconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      backgroundColor: CupertinoColors.systemGroupedBackground,
      navigationBar: const CupertinoNavigationBar(
        middle: Text('蓝牙设备'),
      ),
      child: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: ListView(
                children: [
                  // 状态区
                  Container(
                    color: CupertinoColors.white,
                    padding: const EdgeInsets.symmetric(vertical: 32),
                    child: Column(
                      children: [
                        // 蓝牙状态图标
                        Icon(
                          CupertinoIcons.bluetooth,
                          size: 48,
                          color: _isAdvertising 
                            ? CupertinoColors.activeBlue 
                            : CupertinoColors.systemGrey,
                        ),
                        const SizedBox(height: 16),
                        Text(
                          _status,
                          style: const TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        if (_isAdvertising) ...[
                          const SizedBox(height: 8),
                          Text(
                            '已运行 ${_getRunningTime()}',
                            style: const TextStyle(
                              fontSize: 15,
                              color: CupertinoColors.secondaryLabel,
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),

                  const SizedBox(height: 12),

                  // 操作区
                  Container(
                    color: CupertinoColors.white,
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                    child: Column(
                      children: [
                        // 广播控制按钮
                        SizedBox(
                          width: double.infinity,
                          child: CupertinoButton.filled(
                            padding: const EdgeInsets.symmetric(vertical: 12),
                            onPressed: _isInitialized ? _toggleAdvertising : null,
                            child: Text(
                              _isAdvertising ? '停止广播' : '开始广播',
                              style: const TextStyle(fontSize: 17),
                            ),
                          ),
                        ),
                        const SizedBox(height: 12),
                        // 相机入口
                        SizedBox(
                          width: double.infinity,
                          child: CupertinoButton(
                            padding: const EdgeInsets.symmetric(vertical: 12),
                            color: CupertinoColors.activeGreen,
                            onPressed: () {
                              Navigator.push(
                                context,
                                CupertinoPageRoute(
                                  builder: (context) => CameraPage(
                                    key: _cameraPageKey,
                                    onVideoNameReceived: (name) {
                                      debugPrint('视频已保存: $name');
                                      _bleService.sendVideoName(name);
                                    },
                                  ),
                                ),
                              );
                            },
                            child: const Text(
                              '进入相机',
                              style: TextStyle(
                                  fontSize: 17,
                                  color: CupertinoColors.white
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),

                  const SizedBox(height: 12),

                  // 信息区
                  Container(
                    color: CupertinoColors.white,
                    child: Column(
                      children: [
                        // CupertinoListTile(
                        //   padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 11),
                        //   title: const Text(
                        //     '设备名称',
                        //     style: TextStyle(fontSize: 16),
                        //   ),
                        //   trailing: const Text(
                        //     'BlueRecord',
                        //     style: TextStyle(
                        //       color: CupertinoColors.secondaryLabel,
                        //       fontSize: 16,
                        //     ),
                        //   ),
                        // ),
                        // Container(
                        //   height: 0.5,
                        //   margin: const EdgeInsets.only(left: 16),
                        //   color: CupertinoColors.separator,
                        // ),
                        CupertinoListTile(
                          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 11),
                          title: const Text(
                            '服务 UUID',
                            style: TextStyle(fontSize: 16),
                          ),
                          trailing: Text(
                            BlePeripheralService.getShortUUID(BlePeripheralService.SERVICE_UUID),
                            style: const TextStyle(
                              color: CupertinoColors.secondaryLabel,
                              fontSize: 16,
                            ),
                          ),
                        ),
                        if (_lastCommand.isNotEmpty) ...[
                          Container(
                            height: 0.5,
                            margin: const EdgeInsets.only(left: 16),
                            color: CupertinoColors.separator,
                          ),
                          CupertinoListTile(
                            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 11),
                            title: const Text(
                              '最近命令',
                              style: TextStyle(fontSize: 16),
                            ),
                            subtitle: Text(
                              DateTime.now().toString().substring(11, 19),
                              style: const TextStyle(
                                fontSize: 13,
                                color: CupertinoColors.secondaryLabel,
                              ),
                            ),
                            trailing: Text(
                              _lastCommand,
                              style: const TextStyle(
                                color: CupertinoColors.secondaryLabel,
                                fontSize: 16,
                              ),
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                ],
              ),
            ),

            // 初始化状态提示
            if (!_isInitialized)
              Container(
                padding: const EdgeInsets.all(16),
                color: CupertinoColors.white,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const CupertinoActivityIndicator(),
                    const SizedBox(width: 12),
                    Text(
                      '正在初始化蓝牙服务...',
                      style: TextStyle(
                        color: CupertinoColors.secondaryLabel,
                        fontSize: 15,
                      ),
                    ),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _displayTimer?.cancel();
    _bleService.dispose();
    super.dispose();
  }
} 